notebooks/community/migration/UJ14 legacy AutoML Vision Video Classification.ipynb (1,554 lines of code) (raw):
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "copyright"
},
"outputs": [],
"source": [
"# Copyright 2021 Google LLC\n",
"#\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "title:migration,new"
},
"source": [
"# AutoML SDK: AutoML image classification model\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "install_aip"
},
"source": [
"## Installation\n",
"\n",
"Install the latest (preview) version of AutoML SDK.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "1pHEB-ZsMda_",
"outputId": "babb3ee0-14e0-43fc-afc7-7e6bd608bmigration"
},
"outputs": [],
"source": [
"! pip3 install -U google-cloud-automl --user\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "install_storage"
},
"source": [
"Install the Google *cloud-storage* library as well.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "QnnZhATdMdbB",
"outputId": "5c8e0911-d97b-4bec-bb6d-02f56441ac0d"
},
"outputs": [],
"source": [
"! pip3 install google-cloud-storage\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "restart"
},
"source": [
"### Restart the Kernel\n",
"\n",
"Once you've installed the AutoML SDK and Google *cloud-storage*, you need to restart the notebook kernel so it can find the packages.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "4pKvX2SwMdbD"
},
"outputs": [],
"source": [
"import os\n",
"\n",
"\n",
"if not os.getenv(\"AUTORUN\"):\n",
" # Automatically restart kernel after installs\n",
" import IPython\n",
" app = IPython.Application.instance()\n",
" app.kernel.do_shutdown(True)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "before_you_begin"
},
"source": [
"## Before you begin\n",
"\n",
"### GPU run-time\n",
"\n",
"*Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select* **Runtime > Change Runtime Type > GPU**\n",
"\n",
"### Set up your GCP project\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"1. [Select or create a GCP project](https://console.cloud.google.com/cloud-resource-manager). When you first create an account, you get a $300 free credit towards your compute/storage costs.\n",
"\n",
"2. [Make sure that billing is enabled for your project.](https://cloud.google.com/billing/docs/how-to/modify-project)\n",
"\n",
"3. [Enable the AutoML APIs and Compute Engine APIs.](https://console.cloud.google.com/flows/enableapi?apiid=ml.googleapis.com,compute_component)\n",
"\n",
"4. [Google Cloud SDK](https://cloud.google.com/sdk) is already installed in AutoML Notebooks.\n",
"\n",
"5. Enter your project ID in the cell below. Then run the cell to make sure the\n",
"Cloud SDK uses the right project for all the commands in this notebook.\n",
"\n",
"**Note**: Jupyter runs lines prefixed with `!` as shell commands, and it interpolates Python variables prefixed with `$` into these commands.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "set_project_id"
},
"outputs": [],
"source": [
"PROJECT_ID = \"[your-project-id]\" #@param {type:\"string\"}\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_project_id",
"outputId": "1433ef90-4d91-4070-9201-7c9071cb920f"
},
"outputs": [],
"source": [
"if PROJECT_ID == \"\" or PROJECT_ID is None or PROJECT_ID == \"[your-project-id]\":\n",
" # Get your GCP project id from gcloud\n",
" shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null\n",
" PROJECT_ID = shell_output[0]\n",
" print(\"Project ID:\", PROJECT_ID)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "set_gcloud_project_id",
"outputId": "66d8ef94-2134-4f39-95a9-917619534207"
},
"outputs": [],
"source": [
"! gcloud config set project $PROJECT_ID\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "region"
},
"source": [
"#### Region\n",
"\n",
"You can also change the `REGION` variable, which is used for operations\n",
"throughout the rest of this notebook. Below are regions supported for AutoML. We recommend when possible, to choose the region closest to you.\n",
"\n",
"- Americas: `us-central1`\n",
"- Europe: `europe-west4`\n",
"- Asia Pacific: `asia-east1`\n",
"\n",
"You cannot use a Multi-Regional Storage bucket for training with AutoML. Not all regions provide support for all AutoML services. For the latest support per region, see [Region support for AutoML services]()\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "dZBY6GRCMdbI"
},
"outputs": [],
"source": [
"REGION = 'us-central1' #@param {type: \"string\"}\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "timestamp"
},
"source": [
"#### Timestamp\n",
"\n",
"If you are in a live tutorial session, you might be using a shared test account or project. To avoid name collisions between users on resources created, you create a timestamp for each instance session, and append onto the name of resources which will be created in this tutorial.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "wiCt8N48MdbJ"
},
"outputs": [],
"source": [
"from datetime import datetime\n",
"\n",
"TIMESTAMP = datetime.now().strftime(\"%Y%m%d%H%M%S\")\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "gcp_authenticate"
},
"source": [
"### Authenticate your GCP account\n",
"\n",
"**If you are using AutoML Notebooks**, your environment is already\n",
"authenticated. Skip this step.\n",
"\n",
"*Note: If you are on an AutoML notebook and run the cell, the cell knows to skip executing the authentication steps.*\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "_nBq2y6zMdbK"
},
"outputs": [],
"source": [
"import os\n",
"import sys\n",
"\n",
"# If you are running this notebook in Colab, run this cell and follow the\n",
"# instructions to authenticate your Google Cloud account. This provides access\n",
"# to your Cloud Storage bucket and lets you submit training jobs and prediction\n",
"# requests.\n",
"\n",
"# If on AutoML, then don't execute this code\n",
"if not os.path.exists('/opt/deeplearning/metadata/env_version'):\n",
" if 'google.colab' in sys.modules:\n",
" from google.colab import auth as google_auth\n",
" google_auth.authenticate_user()\n",
"\n",
" # If you are running this tutorial in a notebook locally, replace the string\n",
" # below with the path to your service account key and run this cell to\n",
" # authenticate your Google Cloud account.\n",
" else:\n",
" %env GOOGLE_APPLICATION_CREDENTIALS your_path_to_credentials.json\n",
"\n",
" # Log in to your account on Google Cloud\n",
" ! gcloud auth login\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bucket:batch_prediction"
},
"source": [
"### Create a Cloud Storage bucket\n",
"\n",
"**The following steps are required, regardless of your notebook environment.**\n",
"\n",
"This tutorial is designed to use training data that is in a public Cloud Storage bucket and a local Cloud Storage bucket for your batch predictions. You may alternatively use your own training data that you have stored in a local Cloud Storage bucket.\n",
"\n",
"Set the name of your Cloud Storage bucket below. It must be unique across all Cloud Storage buckets.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "bucket"
},
"outputs": [],
"source": [
"BUCKET_NAME = \"[your-bucket-name]\" #@param {type:\"string\"}\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "autoset_bucket"
},
"outputs": [],
"source": [
"if BUCKET_NAME == \"\" or BUCKET_NAME is None or BUCKET_NAME == \"[your-bucket-name]\":\n",
" BUCKET_NAME = PROJECT_ID + \"aip-\" + TIMESTAMP\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "create_bucket"
},
"source": [
"**Only if your bucket doesn't already exist**: Run the following cell to create your Cloud Storage bucket.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Y5_NZRmyMdbP",
"outputId": "e5a3655d-8cf0-4cbd-9c18-f64bffb4ca00"
},
"outputs": [],
"source": [
"! gsutil mb -l $REGION gs://$BUCKET_NAME\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "validate_bucket"
},
"source": [
"Finally, validate access to your Cloud Storage bucket by examining its contents:\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "aRnzBOTfMdbQ"
},
"outputs": [],
"source": [
"! gsutil ls -al gs://$BUCKET_NAME\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "setup_vars"
},
"source": [
"### Set up variables\n",
"\n",
"Next, set up some variables used throughout the tutorial.\n",
"### Import libraries and define constants\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "import_aip"
},
"source": [
"#### Import AutoML SDK\n",
"\n",
"Import the AutoML SDK into our Python environment.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "z_yz9CUZMdbR"
},
"outputs": [],
"source": [
"import json\n",
"import os\n",
"import sys\n",
"import time\n",
"\n",
"\n",
"from google.cloud import automl_v1beta1 as automl\n",
"\n",
"\n",
"from google.protobuf.json_format import MessageToJson\n",
"from google.protobuf.json_format import ParseDict\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "aip_constants"
},
"source": [
"#### AutoML constants\n",
"\n",
"Setup up the following constants for AutoML:\n",
"\n",
"- `PARENT`: The AutoML location root path for dataset, model and endpoint resources.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "_tmHDZHGMdbS"
},
"outputs": [],
"source": [
"# AutoML location root path for your dataset, model and endpoint resources\n",
"PARENT = \"projects/\" + PROJECT_ID + \"/locations/\" + REGION\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "clients"
},
"source": [
"## Clients\n",
"\n",
"The AutoML SDK works as a client/server model. On your side (the Python script) you will create a client that sends requests and receives responses from the server (AutoML).\n",
"\n",
"You will use several clients in this tutorial, so set them all up upfront.\n",
"\n",
"(?)\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "OiFdpU4mMdbT",
"outputId": "d29dc331-d1f3-494d-ec73-e36176953a10"
},
"outputs": [],
"source": [
"def automl_client():\n",
" return automl.AutoMlClient()\n",
"\n",
"def prediction_client():\n",
" return automl.PredictionServiceClient()\n",
"\n",
"def operations_client():\n",
" return automl.AutoMlClient()._transport.operations_client\n",
"\n",
"clients = {}\n",
"clients[\"automl\"] = automl_client()\n",
"clients[\"prediction\"] = prediction_client()\n",
"clients[\"operations\"] = operations_client()\n",
"\n",
"for client in clients.items():\n",
" print(client)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "import_file:flowers,csv,icn"
},
"outputs": [],
"source": [
"IMPORT_FILE = 'gs://automl-video-demo-data/hmdb_split1.csv'\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "KHJnNxI5xXiS",
"outputId": "7714d066-2301-4b47-d155-d3c5d454def7"
},
"outputs": [],
"source": [
"! gsutil cat $IMPORT_FILE | head -n 10 \n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "datasets_create:migration,new,request"
},
"source": [
"*Example output*:\n",
"```\n",
"TRAIN,gs://automl-video-demo-data/hmdb_split1_5classes_train_inf.csv\n",
"TEST,gs://automl-video-demo-data/hmdb_split1_5classes_test_inf.csv\n",
"```\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "create_a_dataset:migration"
},
"source": [
"## Create a dataset\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "MuX78NX0MdbZ"
},
"source": [
"### [projects.locations.datasets.create](https://cloud.google.com/automl/docs/reference/rest/v1beta1/projects.locations.datasets/create)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "request:migration"
},
"source": [
"#### Request\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "nDWXlqoKcDnf",
"outputId": "bf41d872-b199-4272-b47b-2353b8c3b6cc"
},
"outputs": [],
"source": [
"dataset = {\n",
" \"display_name\": \"hmdb_\" + TIMESTAMP,\n",
" \"video_classification_dataset_metadata\": {}\n",
"}\n",
"\n",
"print(MessageToJson(\n",
" automl.CreateDatasetRequest(\n",
" parent=PARENT,\n",
" dataset=dataset\n",
" ).__dict__[\"_pb\"])\n",
")\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "pSSBWJ49Mdba"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"parent\": \"projects/migration-ucaip-training/locations/us-central1\",\n",
" \"dataset\": {\n",
" \"displayName\": \"hmdb_20210228225744\",\n",
" \"videoClassificationDatasetMetadata\": {}\n",
" }\n",
"}\n",
"```\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "call:migration"
},
"source": [
"#### Call\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "datasets_create:migration,new,call"
},
"outputs": [],
"source": [
"request = clients[\"automl\"].create_dataset(\n",
" parent=PARENT,\n",
" dataset=dataset\n",
")\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "response:migration"
},
"source": [
"#### Response\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "print:migration,new,response",
"outputId": "99f328e4-877e-4d4c-d9a6-6f44a7f03a4c"
},
"outputs": [],
"source": [
"result = request\n",
"\n",
"print(MessageToJson(result.__dict__[\"_pb\"]))\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "datasets_create:migration,new,response"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"name\": \"projects/116273516712/locations/us-central1/datasets/VCN6574174086275006464\",\n",
" \"displayName\": \"hmdb_20210228225744\",\n",
" \"createTime\": \"2021-02-28T23:06:43.197904Z\",\n",
" \"etag\": \"AB3BwFrtf0Yl4fgnXW4leoEEANTAGQdOngyIqdQSJBT9pKEChgeXom-0OyH7dKtfvA4=\",\n",
" \"videoClassificationDatasetMetadata\": {}\n",
"}\n",
"```\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "dataset_id:migration,new,response",
"outputId": "4af2c8c9-84c6-434b-a5c1-0bf199be69f5"
},
"outputs": [],
"source": [
"# The full unique ID for the dataset\n",
"dataset_id = result.name\n",
"# The short numeric ID for the dataset\n",
"dataset_short_id = dataset_id.split('/')[-1]\n",
"\n",
"print(dataset_id)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "cV7PMAk0Mdbi"
},
"source": [
"### [projects.locations.datasets.importData](https://cloud.google.com/automl/docs/reference/rest/v1beta1/projects.locations.datasets/importData)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "BFtdHDpfMdbi"
},
"source": [
"#### Request\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "datasets_import:migration,new,request",
"outputId": "8166381f-48f3-41e6-a86f-f101da50ceaa"
},
"outputs": [],
"source": [
"input_config = {\n",
" \"gcs_source\": {\n",
" \"input_uris\": [IMPORT_FILE]\n",
" }\n",
"}\n",
"\n",
"print(MessageToJson(\n",
" automl.ImportDataRequest(\n",
" name=dataset_short_id,\n",
" input_config=input_config\n",
" ).__dict__[\"_pb\"])\n",
")\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "LzHxgr_6Mdbj"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"name\": \"VCN6574174086275006464\",\n",
" \"inputConfig\": {\n",
" \"gcsSource\": {\n",
" \"inputUris\": [\n",
" \"gs://automl-video-demo-data/hmdb_split1.csv\"\n",
" ]\n",
" }\n",
" }\n",
"}\n",
"```\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "LWRK-vjJMdbk"
},
"source": [
"#### Call\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "datasets_import:migration,new,call"
},
"outputs": [],
"source": [
"request = clients[\"automl\"].import_data(\n",
" name=dataset_id,\n",
" input_config=input_config\n",
")\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "bUrXTi34Mdbl"
},
"source": [
"#### Response\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "fETkBwGaMdbl",
"outputId": "431361a6-8a4a-408b-b6f8-d631d2b6fe69"
},
"outputs": [],
"source": [
"result = request.result()\n",
"\n",
"print(MessageToJson(result))\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "datasets_import:migration,new,response"
},
"source": [
"*Example output*:\n",
"```\n",
"{}\n",
"```\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "train_a_model:migration"
},
"source": [
"## Train a model\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "text_models_create:migration,old"
},
"source": [
"### [projects.locations.models.create](https://cloud.google.com/automl/docs/reference/rest/v1beta1/projects.locations.models/create)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "XhbhTx6DMdbo"
},
"source": [
"#### Request\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "trainingpipelines_create:migration,new,request,icn",
"outputId": "aaa36418-7aa8-4b6b-8b06-5343fa1b35e0"
},
"outputs": [],
"source": [
"model = {\n",
" \"display_name\": \"hmdb_\" + TIMESTAMP,\n",
" \"dataset_id\": dataset_short_id,\n",
" \"video_classification_model_metadata\": {}\n",
"}\n",
"\n",
"print(MessageToJson(\n",
" automl.CreateModelRequest(\n",
" parent=PARENT,\n",
" model=model\n",
" ).__dict__[\"_pb\"])\n",
")\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "1__HJXz0Mdbq"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"parent\": \"projects/migration-ucaip-training/locations/us-central1\",\n",
" \"model\": {\n",
" \"displayName\": \"hmdb_20210228225744\",\n",
" \"datasetId\": \"VCN6574174086275006464\",\n",
" \"videoClassificationModelMetadata\": {}\n",
" }\n",
"}\n",
"```\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "8_Z5loUyMdbq"
},
"source": [
"#### Call\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "trainingpipelines_create:migration,new,call"
},
"outputs": [],
"source": [
"request = clients[\"automl\"].create_model(\n",
" parent=PARENT,\n",
" model=model\n",
")\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "fZLpwN_dMdbr"
},
"source": [
"#### Response\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "print:migration,new,request",
"outputId": "7e7f19e1-771d-4e4e-8edc-87eab3672b9e"
},
"outputs": [],
"source": [
"result = request.result()\n",
"\n",
"print(MessageToJson(result.__dict__[\"_pb\"]))\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "trainingpipelines_create:migration,new,response,icn"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"name\": \"projects/116273516712/locations/us-central1/models/VCN6188818900239515648\"\n",
"}\n",
"```\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "training_pipeline_id:migration,new,response",
"outputId": "0de12c6d-ffac-470e-d39e-0d0b1a92f4c0"
},
"outputs": [],
"source": [
"# The full unique ID for the training pipeline\n",
"model_id = result.name\n",
"# The short numeric ID for the training pipeline\n",
"model_short_id = model_id.split('/')[-1]\n",
"\n",
"print(model_short_id)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "evaluate_the_model:migration"
},
"source": [
"## Evaluate the model\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "yfufMwAEJjkX"
},
"source": [
"### [projects.locations.models.modelEvaluations.list](https://cloud.google.com/automl/docs/reference/rest/v1beta1/projects.locations.models.modelEvaluations/list)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "x6tyDgg2Mdbt"
},
"source": [
"#### Call\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "models_evaluations_list:migration,new,call"
},
"outputs": [],
"source": [
"request = clients[\"automl\"].list_model_evaluations(\n",
" parent=model_id\n",
")\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "Pz4WmA2SMdbu"
},
"source": [
"#### Response\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "AxEY7WFHj2YC",
"outputId": "e284ae12-dbb8-4b8f-c576-03d23cc822af"
},
"outputs": [],
"source": [
"import json\n",
"\n",
"\n",
"model_evaluations = [\n",
" json.loads(MessageToJson(me.__dict__[\"_pb\"])) for me in request \n",
"]\n",
"# The evaluation slice\n",
"evaluation_slice = request.model_evaluation[0].name\n",
"\n",
"print(json.dumps(model_evaluations, indent=2))\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "models_evaluations_list:migration,new,response,icn"
},
"source": [
"*Example output*\n",
"```\n",
"[\n",
" {\n",
" \"name\": \"projects/116273516712/locations/us-central1/models/VCN6188818900239515648/modelEvaluations/1998146574672720266\",\n",
" \"createTime\": \"2021-03-01T01:02:02.452298Z\",\n",
" \"evaluatedExampleCount\": 150,\n",
" \"classificationEvaluationMetrics\": {\n",
" \"auPrc\": 1.0,\n",
" \"confidenceMetricsEntry\": [\n",
" {\n",
" \"confidenceThreshold\": 0.016075565,\n",
" \"recall\": 1.0,\n",
" \"precision\": 0.2,\n",
" \"f1Score\": 0.33333334\n",
" },\n",
" {\n",
" \"confidenceThreshold\": 0.017114623,\n",
" \"recall\": 1.0,\n",
" \"precision\": 0.202977,\n",
" \"f1Score\": 0.3374578\n",
" },\n",
" \n",
" # REMOVED FOR BREVITY\n",
" \n",
" {\n",
" \"confidenceThreshold\": 0.9299338,\n",
" \"recall\": 0.033333335,\n",
" \"precision\": 1.0,\n",
" \"f1Score\": 0.06451613\n",
" }\n",
" ]\n",
" },\n",
" \"displayName\": \"golf\"\n",
" }\n",
"]\n",
"```\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "i6T0bzuNJjkY"
},
"source": [
"### [projects.locations.models.modelEvaluations.get](https://cloud.google.com/automl/docs/reference/rest/v1beta1/projects.locations.models.modelEvaluations/get)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "0FoWkw05Mdb0"
},
"source": [
"#### Call\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "models_evaluations_get:migration,new,call"
},
"outputs": [],
"source": [
"request = clients[\"automl\"].get_model_evaluation(\n",
" name=evaluation_slice\n",
")\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "u2H0pOs9Mdb1"
},
"source": [
"#### Response\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "IlGAsJM2Mdb1",
"outputId": "14f4d517-f948-455b-8cfe-0658e4320c94",
"scrolled": true
},
"outputs": [],
"source": [
"print(MessageToJson(request.__dict__[\"_pb\"]))\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "models_evaluations_get:migration,new,response,icn"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"name\": \"projects/116273516712/locations/us-central1/models/VCN6188818900239515648/modelEvaluations/1998146574672720266\",\n",
" \"createTime\": \"2021-03-01T01:02:02.452298Z\",\n",
" \"evaluatedExampleCount\": 150,\n",
" \"classificationEvaluationMetrics\": {\n",
" \"auPrc\": 1.0,\n",
" \"confidenceMetricsEntry\": [\n",
" {\n",
" \"confidenceThreshold\": 0.016075565,\n",
" \"recall\": 1.0,\n",
" \"precision\": 0.2,\n",
" \"f1Score\": 0.33333334\n",
" },\n",
" {\n",
" \"confidenceThreshold\": 0.017114623,\n",
" \"recall\": 1.0,\n",
" \"precision\": 0.202977,\n",
" \"f1Score\": 0.3374578\n",
" },\n",
" \n",
" # REMOVED FOR BREVITY\n",
" \n",
" {\n",
" \"confidenceThreshold\": 0.9299338,\n",
" \"recall\": 0.006666667,\n",
" \"precision\": 1.0,\n",
" \"f1Score\": 0.013245033\n",
" }\n",
" ],\n",
" \"confusionMatrix\": {\n",
" \"annotationSpecId\": [\n",
" \"175274248095399936\",\n",
" \"2048771693081526272\",\n",
" \"4354614702295220224\",\n",
" \"6660457711508914176\",\n",
" \"8966300720722608128\"\n",
" ],\n",
" \"row\": [\n",
" {\n",
" \"exampleCount\": [\n",
" 30,\n",
" 0,\n",
" 0,\n",
" 0,\n",
" 0\n",
" ]\n",
" },\n",
" {\n",
" \"exampleCount\": [\n",
" 0,\n",
" 30,\n",
" 0,\n",
" 0,\n",
" 0\n",
" ]\n",
" },\n",
" {\n",
" \"exampleCount\": [\n",
" 0,\n",
" 0,\n",
" 30,\n",
" 0,\n",
" 0\n",
" ]\n",
" },\n",
" {\n",
" \"exampleCount\": [\n",
" 0,\n",
" 0,\n",
" 0,\n",
" 30,\n",
" 0\n",
" ]\n",
" },\n",
" {\n",
" \"exampleCount\": [\n",
" 0,\n",
" 0,\n",
" 0,\n",
" 0,\n",
" 30\n",
" ]\n",
" }\n",
" ],\n",
" \"displayName\": [\n",
" \"ride_horse\",\n",
" \"golf\",\n",
" \"cartwheel\",\n",
" \"pullup\",\n",
" \"kick_ball\"\n",
" ]\n",
" }\n",
" }\n",
"}\n",
"```\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "make_batch_predictions:migration"
},
"source": [
"## Make batch predictions\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "make_batch_file:automl,image"
},
"source": [
"### Make the batch input file\n",
"\n",
"To request a batch of predictions from AutoML Video, create a CSV file that lists the Cloud Storage paths to the videos that you want to annotate. You can also specify a start and end time to tell AutoML Video to only annotate a segment (segment-level) of the video. The start time must be zero or greater and must be before the end time. The end time must be greater than the start time and less than or equal to the duration of the video. You can also use inf to indicate the end of a video.\n",
"\n",
"example: \n",
" `gs://my-videos-vcm/short_video_1.avi,0.0,5.566667` \n",
" `gs://my-videos-vcm/car_chase.avi,0.0,3.933333` \n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "get_test_items:automl,icn,csv",
"outputId": "5eed7f11-5c61-4fdc-9f65-96a31e4f1313"
},
"outputs": [],
"source": [
"TRAIN_FILES = \"gs://automl-video-demo-data/hmdb_split1_5classes_train_inf.csv\"\n",
"\n",
"test_items = ! gsutil cat $TRAIN_FILES | head -n2\n",
"\n",
"cols = str(test_items[0]).split(',')\n",
"test_item_1, test_label_1, test_start_1, test_end_1 = str(cols[0]), str(cols[1]), str(cols[2]), str(cols[3])\n",
"print(test_item_1, test_label_1)\n",
"\n",
"cols = str(test_items[1]).split(',')\n",
"test_item_2, test_label_2, test_start_2, test_end_2 = str(cols[0]), str(cols[1]), str(cols[2]), str(cols[3])\n",
"print(test_item_2, test_label_2)\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "aZYEuzIccDnq"
},
"source": [
"*Example output*:\n",
"```\n",
"gs://automl-video-demo-data/hmdb51/_Rad_Schlag_die_Bank__cartwheel_f_cm_np1_le_med_0.avi cartwheel\n",
"gs://automl-video-demo-data/hmdb51/Acrobacias_de_un_fenomeno_cartwheel_f_cm_np1_ba_bad_8.avi cartwheel\n",
"```\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "tK_A0CKQMdcF",
"outputId": "9effe058-4f8c-4312-9cd3-15869bd206c8"
},
"outputs": [],
"source": [
"import tensorflow as tf\n",
"import json\n",
"\n",
"gcs_input_uri = \"gs://\" + BUCKET_NAME + '/test.csv'\n",
"with tf.io.gfile.GFile(gcs_input_uri, 'w') as f:\n",
" data = f\"{test_item_1}, {test_start_1}, {test_end_1}\"\n",
" f.write(data + '\\n')\n",
" data = f\"{test_item_2}, {test_start_2}, {test_end_2}\"\n",
" f.write(data + '\\n')\n",
" \n",
"print(gcs_input_uri)\n",
"! gsutil cat $gcs_input_uri\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "JjkG44EScDnq"
},
"source": [
"*Example output*:\n",
"```\n",
"gs://migration-ucaip-trainingaip-20210228225744/test.csv\n",
"gs://automl-video-demo-data/hmdb51/_Rad_Schlag_die_Bank__cartwheel_f_cm_np1_le_med_0.avi, 0.0, inf\n",
"gs://automl-video-demo-data/hmdb51/Acrobacias_de_un_fenomeno_cartwheel_f_cm_np1_ba_bad_8.avi, 0.0, inf\n",
"```\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "text_models_batchpredict:migration,old"
},
"source": [
"### [projects.locations.models.batchPredict](https://cloud.google.com/automl/docs/reference/rest/v1beta1/projects.locations.models/batchPredict)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "YvQJiFamMdcG"
},
"source": [
"#### Request\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "batchpredictionjobs_create:migration,new,request,icn",
"outputId": "6ffce530-ea59-4b6b-c990-5cd684cc4c22"
},
"outputs": [],
"source": [
"input_config = {\n",
" \"gcs_source\": {\n",
" \"input_uris\": [gcs_input_uri]\n",
" }\n",
"}\n",
"\n",
"output_config = {\n",
" \"gcs_destination\": {\n",
" \"output_uri_prefix\": \"gs://\" + f\"{BUCKET_NAME}/batch_output/\"\n",
" }\n",
"}\n",
"\n",
"batch_prediction = automl.BatchPredictRequest(\n",
" name=model_id,\n",
" input_config=input_config,\n",
" output_config=output_config\n",
")\n",
" \n",
"print(MessageToJson(\n",
" batch_prediction.__dict__[\"_pb\"])\n",
")\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "zlU4Mbd5MdcJ"
},
"source": [
"*Example output*:\n",
"```\n",
"{\n",
" \"name\": \"projects/116273516712/locations/us-central1/models/VCN6188818900239515648\",\n",
" \"inputConfig\": {\n",
" \"gcsSource\": {\n",
" \"inputUris\": [\n",
" \"gs://migration-ucaip-trainingaip-20210228225744/test.csv\"\n",
" ]\n",
" }\n",
" },\n",
" \"outputConfig\": {\n",
" \"gcsDestination\": {\n",
" \"outputUriPrefix\": \"gs://migration-ucaip-trainingaip-20210228225744/batch_output/\"\n",
" }\n",
" }\n",
"}\n",
"```\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "qjugtUM7MdcJ"
},
"source": [
"#### Call\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "batchpredictionjobs_create:migration,new,call"
},
"outputs": [],
"source": [
"request = clients[\"prediction\"].batch_predict(\n",
" request=batch_prediction\n",
")\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "u1lEkLr8MdcK"
},
"source": [
"#### Response\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Q6HGGVlaMdcK",
"outputId": "160c9c08-f46a-4e07-cb7e-b558ddd23a39"
},
"outputs": [],
"source": [
"result = request.result()\n",
"\n",
"print(MessageToJson(result.__dict__[\"_pb\"]))\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "batchpredictionjobs_create:migration,new,response,icn"
},
"source": [
"*Example output*:\n",
"\n",
"```\n",
"{}\n",
"```\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "cleanup:migration,new"
},
"source": [
"# Cleaning up\n",
"\n",
"To clean up all GCP resources used in this project, you can [delete the GCP\n",
"project](https://cloud.google.com/resource-manager/docs/creating-managing-projects#shutting_down_projects) you used for the tutorial.\n",
"\n",
"Otherwise, you can delete the individual resources you created in this tutorial.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "wuJTfRWNMdcL",
"outputId": "4e7f019b-c477-42db-ae3f-4a3a78e1df88"
},
"outputs": [],
"source": [
"delete_dataset = True\n",
"delete_model = True\n",
"delete_bucket = True\n",
"\n",
"# Delete the dataset using the AutoML fully qualified identifier for the dataset\n",
"try:\n",
" if delete_dataset:\n",
" clients['automl'].delete_dataset(name=dataset_id)\n",
"except Exception as e:\n",
" print(e)\n",
"\n",
"# Delete the model using the AutoML fully qualified identifier for the model\n",
"try:\n",
" if delete_model:\n",
" clients['automl'].delete_model(name=model_id)\n",
"except Exception as e:\n",
" print(e)\n",
"\n",
"if delete_bucket and 'BUCKET_NAME' in globals():\n",
" ! gsutil rm -r gs://$BUCKET_NAME\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"id": "Z5i6Q68BcDns"
},
"outputs": [],
"source": []
}
],
"metadata": {
"colab": {
"name": "[UJ.14 OLD] AutoML Vision Video Classification.ipynb",
"provenance": [],
"toc_visible": true
},
"environment": {
"name": "tf2-2-3-gpu.2-3.m55",
"type": "gcloud",
"uri": "gcr.io/deeplearning-platform-release/tf2-2-3-gpu.2-3:m55"
},
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.8"
}
},
"nbformat": 4,
"nbformat_minor": 4
}